package com.yuandengta.yomall.search.service.impl;

import com.yuandengta.common.to.es.SkuEsModel;
import com.yuandengta.common.utils.JsonUtils;
import com.yuandengta.yomall.search.config.ElasticSearchConfig;
import com.yuandengta.yomall.search.constant.EsConstant;
import com.yuandengta.yomall.search.service.ProductServcie;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品服务 {@link ProductServiceImpl}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductServcie {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 商品上架
     * @param skuEsModelList
     */
    @Override
    public boolean productUp(List<SkuEsModel> skuEsModelList) throws IOException {
        // 给 es 中建立索引，并建立好映射关系
        // ES批量保存
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModelList.forEach(skuEsModel -> {
            // 指定索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 指定索引id
            indexRequest.id(skuEsModel.getSkuId().toString());
            // 转换为json
            String jsonString = JsonUtils.objectToJson(skuEsModel);
            // 设置数据
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        // TODO 处理批量保存错误
        // true 有错误，false 没有错误
        boolean b = bulk.hasFailures();
        // 记录日志
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架：{}", collect);

        return b;
    }
}
